package com.coding365.service.user.service.impl;

import com.coding365.service.user.config.OauthServerConfiger;
import com.coding365.service.user.config.SecurityConfiger;
import com.coding365.service.user.dao.LagouAuthCodeMapper;
import com.coding365.service.user.dao.LagouTokenMapper;
import com.coding365.service.user.entity.LagouAuthCode;
import com.coding365.service.user.entity.LagouToken;
import com.coding365.service.user.rpc.CodeFeignClient;
import com.coding365.service.user.rpc.UserFeignClient;
import com.coding365.service.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Autowired
    private CodeFeignClient codeFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private LagouTokenMapper lagouTokenMapper;

    @Override
    public Boolean register(String email, String password, String code, HttpServletResponse response) {
        //调用lagou-service-code验证验证码是否正确
        Integer result = codeFeignClient.validateCode(email, code);
        //验证错误返回false
        if (result == null || !result.equals(0)){
            return false;
        }
        //生成access_token并存入数据库

        return  createToken(email, password,response);
    }

    @Override
    public Boolean isRegistered(String email) {
        LagouToken lagouToken = lagouTokenMapper.selectLagouTokenWithEmail(email);
        if (lagouToken == null){
            return false;
        }
        return true;
    }

    @Override
    public Boolean login(String email, String password,HttpServletResponse response) {
        LagouToken lagouToken = lagouTokenMapper.selectLagouTokenWithEmail(email);
        if (lagouToken == null){
            return false;
        }
        return createToken(email,password,response);
    }


    private Boolean createToken(String email,
                                String password,
                                HttpServletResponse response){


        try {
            if (lagouTokenMapper.selectLagouTokenWithEmail(email) == null){
                LagouToken lagouToken = new LagouToken();
                lagouToken.setEmail(email);
                lagouToken.setPassword(password);
                lagouTokenMapper.insertLagouToken(lagouToken);
            }

            ResponseEntity<OAuth2AccessToken> oAuth2AccessToken = userFeignClient.oauthToken(OauthServerConfiger.clientSecret, OauthServerConfiger.grantType, email, password, OauthServerConfiger.clientId);
        if (oAuth2AccessToken == null
                || !oAuth2AccessToken.getStatusCode().equals(HttpStatus.OK)){
            return false;
        }

        String token = oAuth2AccessToken.getBody().getValue();
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        lagouTokenMapper.updateLagouToken(email,token);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;

    }

    @Override
    public String getUserInfo(String token) {
        if (StringUtils.isEmpty(token)){
            return "";
        }
        String email = "";
        try {
            Map<String, ?> stringMap = userFeignClient.checkToken(token);
            if (stringMap != null && stringMap.get("user_name") != null){
                email = (String) stringMap.get("user_name");
            }
        }catch (Exception e){
            return "";
        }
        return email;
    }
}
